#include <Ice/Application.h>
#include <FileTransfer.h>
#include <time.h>

using namespace std;
using namespace Ice;
using namespace FileTransfer;

class Client
  : virtual public Ice::Application
{
public:
  virtual int run (int argc,
		   char *argv[])
  {
    Ice::ObjectPrx base = communicator()->
      stringToProxy("FileStore:tcp -h 161.67.38.113 -p 10000");
    FileStorePrx fileStorePrx = FileStorePrx::checkedCast(base);

    if (argc < 2) {
      cout << "Synopsis: ./Client <file_to_transfer>" << endl;
      return EXIT_FAILURE;
    }

    string name = argv[1];
    FILE* fp = fopen(name.c_str(), "wb");
    Ice::ByteSeq data;
    int offset = 0;
    int len = 1000 * 1024;
    time_t begin = 0, end = 0;

    begin = time(NULL);
    for (;;) {
      try {
	data = fileStorePrx-> read(name, offset, len);
      }
      catch (FileAccessException ex) {
	cout << ex.reason << endl;
	break;
      }
      if (data.size() == 0) {
	break;
      }
      if (fwrite(&data[0], 1, data.size(), fp)
	  != data.size()) {
	cerr << "error writing: " << strerror(errno) << endl;
	break;
      }
      offset += data.size();
    }

    fclose(fp);
    end = time(NULL);

    cout << "Seconds employed: " << end - begin << endl;

    communicator()->waitForShutdown();
    return EXIT_SUCCESS;
  }
};

int main(int argc,
	 char* argv[])
{
  Client client;
  return client.main(argc, argv);
}
